package com.taocares.sfss.config;

import com.mongodb.*;
import com.taocares.sfss.config.properties.MongoDbProperties;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;

@Configuration
public class MongoDbConfig extends AbstractMongoConfiguration {

	private final MongoDbProperties properties;

	@Autowired
	public MongoDbConfig(MongoDbProperties properties) {
		this.properties = properties;
	}

	@Bean
	public MongoClient mongoClient() {
		MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(properties.getConnectionsPerHost().intValue()).minConnectionsPerHost(properties.getMinConnectionsPerHost().intValue()).threadsAllowedToBlockForConnectionMultiplier(properties.getThreadsAllowedToBlockForConnectionMultiplier().intValue()).serverSelectionTimeout(properties.getServerSelectionTimeout().intValue()).maxWaitTime(properties.getMaxWaitTime().intValue()).maxConnectionIdleTime(properties.getMaxConnectionIdleTime().intValue()).maxConnectionLifeTime(properties.getMaxConnectionLifeTime().intValue()).connectTimeout(properties.getConnectTimeout().intValue()).socketTimeout(properties.getSocketTimeout().intValue()).sslEnabled(properties.getSslEnabled().booleanValue()).sslInvalidHostNameAllowed(properties.getSslInvalidHostNameAllowed().booleanValue()).alwaysUseMBeans(properties.getAlwaysUseMBeans().booleanValue()).heartbeatConnectTimeout(properties.getHeartbeatConnectTimeout().intValue()).heartbeatSocketTimeout(properties.getHeartbeatSocketTimeout().intValue()).minHeartbeatFrequency(properties.getMinHeartbeatFrequency().intValue()).heartbeatFrequency(properties.getHeartbeatFrequency().intValue()).localThreshold(properties.getLocalThreshold().intValue()).build();
		List serverAddressList = new ArrayList();
		ServerAddress serverAddress;
		for (Iterator iterator = properties.getAddress().iterator(); iterator.hasNext(); serverAddressList.add(serverAddress)) {
			String address = (String)iterator.next();
			String hostAndPort[] = address.split(":");
			String host = hostAndPort[0];
			Integer port = Integer.valueOf(Integer.parseInt(hostAndPort[1]));
			serverAddress = new ServerAddress(host, port.intValue());
		}

		if (properties.getUsername() != null && properties.getPassword() != null) {
			MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(properties.getUsername(), properties.getAuthenticationDatabase() == null ? properties.getDatabase() : properties.getAuthenticationDatabase(), properties.getPassword().toCharArray());
			return new MongoClient(serverAddressList, mongoCredential, options);
		} else {
			return new MongoClient(serverAddressList, options);
		}
	}

	protected String getDatabaseName() {
		return properties.getDatabase();
	}
}
